/**
 * com.dingjian.base.dao.impl.QueryExecutorImpl.java
 * 2012-6-20
 */
package com.dingjian.base.dao.impl;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.dingjian.base.common.Pagination;
import com.dingjian.base.dao.QueryExecutor;
import com.dingjian.base.mybatis.interceptor.ExecutorInterceptor;
import com.dingjian.base.util.StringUtils;

/**
 * 
 * @author FengMy
 * @since 2012-6-20下午03:58:29
 */
@Component(value="queryExecutor")
public class QueryExecutorImpl extends SqlSessionDaoSupport implements QueryExecutor {
	@Autowired
	protected SqlSessionFactory sqlSessionFactory;
	@Autowired
	protected JdbcTemplate jdbcTemplate;
	@SuppressWarnings("unchecked")
	@Override
	public <T> Pagination<T> execQuery(String mapper,Pagination<T> pagination,
			Map<String, Object> param) {
		if(StringUtils.isEmpty(mapper)){
			throw new IllegalArgumentException("mapper could not to be empty");
		}
		int count = (Integer) getSqlSession().selectOne(mapper, new ExecutorInterceptor.CountParameter(param));
		pagination.setRecordCount(count);
		List<T> list = getSqlSession().selectList(mapper, param, new RowBounds((pagination.getCurrentPage() - 1) * pagination.getPageSize(), pagination.getPageSize()));
		pagination.setItems(list);
		return pagination;
	}

	@SuppressWarnings("unchecked")
	@Override
	public <T> List<T> execQuery(String mapper, Map<String, Object> param,Class<T> type) {
		if(StringUtils.isEmpty(mapper)){
			throw new IllegalArgumentException("mapper could not to be empty");
		}
		return getSqlSession().selectList(mapper, param);
	}
	
	@Override
	public int execCount(String mapper, Map<String, Object> param){
		if(StringUtils.isEmpty(mapper)){
			throw new IllegalArgumentException("mapper could not to be empty");
		}
		int count = (Integer) getSqlSession().selectOne(mapper, new ExecutorInterceptor.CountParameter(param));
		return count;
	}

	@Override
	public void executeInsert(String mapper, Object param){
		getSqlSession().insert(mapper, param);
	}

	@Override
	public void executeUpdate(String mapper, Object param){
		getSqlSession().update(mapper, param);
	}

	@Override
	public void executeDelete(String mapper, Object param){
		getSqlSession().delete(mapper, param);
	}
}
